<*****课件视频*****>
<template>
  <div id="expVideo" style="height: 100%;">
    <!---->
    <Row v-if="videoLists.length > 0 && videoLists[0]">
      <h3 style="float:left;" :style="type == 'EduPdf' ? 'margin-bottom:10px' : ''">
        {{ videoLists[0].srcname }}
      </h3>
      <!-- <Button @click="gotoDoc" v-if="type == 'EduPdf'" size="small" type="primary" icon="ios-expand" style="margin: 0 0 10px 10px;float:right;" :disabled="!videoLists[0].srcname">全屏查看</Button> -->
    </Row>
    <template v-if="type == 'EduVideo'">
      <Row>
        <!--<h3 style="float:left;" v-if="videoLists.length > 0 && videoLists[0]">{{videoLists[0].srcname}}</h3>-->
        <!--<Button @click="addVideo" size="small" type="primary" class="md-add-jh" style="margin: 0 0 10px 10px;float:right;" :disabled="isDisable || status" v-if="videoLists.length == 0">添加视频</Button>-->
        <!--<Button @click="addVideo" size="small" type="primary" icon="ios-refresh" style="margin: 0 0 10px 10px;float:right;" :disabled="isDisable || status" v-if="videoLists.length > 0">更新视频</Button>-->
        <!--<Poptip
	          transfer
	          confirm
	          style="float: right"
	          title="删除视频"
	          @on-ok="deleteVideo(videoLists[0])"
	          @on-cancel="cancel" v-if="videoLists.length > 0">
	          <Button type="error" size="small" :disabled="isDisable || status">删除</Button>
	        </Poptip>-->
      </Row>
      <div v-if="isFlv" class="video" ref="view-play" style="width:100%;margin-top:10px;height:100%;"></div>
      <!-- <Divider style="margin-top:10px;"></Divider> -->
      <video
        v-else
        :src="videoSrc(videoLists[0])"
        poster="../../../assets/globalIcon/videoBg.png"
        controls="controls"
        style="width:100%;margin-top:10px;height:100%;"
        id="learnVideo"
        v-show="showDataList"
      >
        您的浏览器不支持 video 标签。
      </video>
      <div v-show="showDefImg" class="defGraphWrap">
        <div class="defGraph"></div>
        <div class="graphText">暂无信息</div>
      </div>
      <!--<div v-for="video in videoLists" :key="video.srcid" class="video-wrap" v-if="videoLists.length > 0">
		<div style="display: inline-block">
			<Icon size="18" type="ios-videocam" /> 
			<a :href="videoSrc(video)" target="_blank">{{video.srcname}}</a>
		</div>
		<Poptip
			transfer
			confirm
			style="float: right"
			title="删除视频"
			@on-ok="deleteVideo(video)"
			@on-cancel="cancel">
			<Button type="error" size="small" :disabled="isDisable || status" >删除</Button>
		</Poptip>
		<Divider dashed />
		</div>-->
      <!--<Table border :columns="getUploadVideoCol" :data="videoLists" v-show="false"></Table>-->
      <!--添加视频-->
      <Modal
        v-model="addVideoModal"
        :mask-closable="false"
        title="添加视频"
        :loading="addVideoLoading"
        width="800"
        @on-ok="asyncOK"
      >
        <div
          style="display:flex;justify-content: space-between;align-items: center;margin-bottom:10px;"
        >
          已选择视频：{{ this.userVideoName }}
          <Input
            v-model.trim="queryFileName"
            placeholder="请输入文件名称"
            style="width: 150px;"
            clearable
            @on-change="changePage(1)"
          />
        </div>
        <Table border :columns="getUploadVideoCol" :data="getUploadVideoList"></Table>
        <Page
          :total="videoTotal"
          :current="queryVideoInfo.pageIndex"
          show-elevator
          show-total
          @on-change="changePage"
          style="text-align:center;margin-top:10px;"
        />
      </Modal>
    </template>
    <template v-else>
      <div class="expDoc" v-show="showDataList && docLoadCompete && docLoaded">
        <!-- <iframe :src="'/api/minio/filePreview?path='+videoLists[0].srcpath" v-if="videoLists[0]" width="100%" height="100%" id="expDoc" scrolling="no" @load="loadDoc"></iframe> -->
        <guideIframeVue
          @loads="loadDoc"
          v-if="videoLists[0]"
          :showDefImg="showDefImg"
          :mdPath="videoLists[0].srcpath"
          :guideSrc="`/api/minio/filePreview?path=${videoLists[0].srcpath}`"
          :fileName="videoLists[0].srcname"
          :fileId="videoLists[0].fileId"
          :contentHeiNei="contentHeiNei"
          :type="0"
        ></guideIframeVue>
      </div>
      <div
        v-show="showDefImg || !docLoadCompete || (docLoadCompete && !docLoaded)"
        class="defGraphWrap"
      >
        <div class="defGraph"></div>
        <div class="graphText" v-if="showDefImg">暂无信息</div>
        <div class="graphText" v-else-if="!docLoadCompete">加载中...</div>
        <div class="graphText" v-else>
          课件加载失败{{ loadErrorMessage ? ':' + loadErrorMessage : '' }}
        </div>
      </div>
    </template>
  </div>
</template>

<script>
import {
  getVideoDetail,
  addExpVideo,
  delExpVideo,
  modifyExpVideo
} from '@/api/selfStudy/courseExp.js';
import { getFilesData } from '@/api/uploadFile.js';
import encryption from '@/libs/encryption.js';
import guideIframeVue from './guideIframe.vue';
export default {
  name: 'expVideo',
  props: ['ecid', 'status', 'type', 'contentHeiNei'],
  components: { guideIframeVue },
  data() {
    return {
      USER_ID: '',
      USER_Name: '',
      isDisable: false,
      videoLists: [],
      addVideoModal: false,
      addVideoLoading: true,
      getUploadVideoList: [],
      getUploadVideoCol: [
        {
          title: '名称',
          key: 'originName',
          align: 'center'
        },
        {
          title: '文件路径',
          key: 'path',
          align: 'center'
        },
        {
          title: '文件类型',
          key: 'bucket',
          align: 'center'
        },
        {
          title: '文件大小',
          key: 'size',
          align: 'center'
        },
        {
          title: '创建时间',
          key: 'created',
          align: 'center'
        },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          render: (h, params) => {
            console.log(params.row.selected);
            return h('div', [
              h(
                'Button',
                {
                  props: {
                    disabled: params.row.selected,
                    type: 'primary',
                    size: 'small'
                  },
                  on: {
                    click: () => {
                      this.useVideo(params);
                    }
                  }
                },
                '使用'
              )
            ]);
          }
        }
      ],
      getUploadVideoRow(val) {
        let data = [];
        for (let i = 0; i < val.length; i++) {
          data.push({
            fileName: val[i]['originName'],
            filePath: val[i]['path'],
            fileTime: val[i]['created'],
            fileId: val[i]['id'],
            fileSize: val[i]['size'],
            fileType: val[i]['bucket'],
            selected: val[i]['selected'],
            duration: val[i]['duration']
          });
        }
        return data;
      },
      userVideo: {},
      userVideoName: '',
      userVideoPath: '',
      queryVideoInfo: {
        pageIndex: 1,
        pageSize: 10
      },
      queryFileName: '',
      videoTotal: 0,
      showDataList: true,
      showDefImg: false,
      docLoaded: false,
      docLoadCompete: false,
      loadErrorMessage: '',
      isFlv: false,
      flagEduPdf :true,
      flagEduVideo:true
    };
  },
  watch: {
    type: function() {
      this.getVideoList();
    }
  },
  filters: {},
  computed: {},
  mounted() {
    // 获取用户id
    let November = sessionStorage.getItem('November');
    November = JSON.parse(encryption.SelfUseDecrypt(November));
    this.USER_ID = November.userId;
    this.getVideoList();
    //	    this.isRootDesigner = November.isRootDesigner
  },
  beforeDestroy() {},
  methods: {
    // 获取视频列表
    getVideoList() {
      if(this.$refs['view-play']){
        this.$refs['view-play'].innerHTML = '';
      }
      
      getVideoDetail(this.ecid, { srcType: this.type })
        .then((data) => {
          // 
          if (data.code == 1) {
            this.videoLists = data.attribute.data;
            this.isFlv = false;
            if (this.videoLists.length > 0) {
              this.showDataList = true;
              this.showDefImg = false;
              if (this.videoLists[0].srcpath.split('.').pop() == 'flv') {
                this.isFlv = true;
                setTimeout(() => {
                  var videoObject = {
                    container: '.video', //“#”代表容器的ID，“.”或“”代表容器的class
                    plug: 'flv.js', //设置使用flv插件
                    video: this.videoSrc(this.videoLists[0]) //视频地址
                  };
                  new ckplayer(videoObject); //初始化播放器
                });
              }
            } else {
              this.showDataList = false;
              this.showDefImg = true;
            }
          } else if (data.code == 0) {
            this.videoLists = [];
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    videoSrc(item) {
      if (item) {
        return `/Learn/${item.srcpath}`;
      } else {
        return '';
      }
    },
    addVideo() {
      this.queryVideoInfo.pageIndex = 1;
      this.addVideoModal = true;
      this.userVideoName = this.videoLists.length > 0 ? this.videoLists[0].srcname : '';
      this.queryUploadList();
    },
    // 查询上传的视频列表
    queryUploadList() {
      //	      this.axios.get(`/api/ftp/filerecord?fileType=.mp4&operatorid=${this.USER_ID}`,{
      //	        headers:{'Content-Type': 'application/json'}
      //	      })
      //			let params = {
      //				page:1,
      //				rows:2000000,
      //				fileCatalog:'videos',
      //				isPublic:1
      //			};
      let data = {
        bucket: 'videos'
      };
      if (this.queryFileName) {
        data.originName = this.queryFileName;
      }
      getFilesData(this.queryVideoInfo, data)
        .then((res) => {
          // console.log(res)
          let data = res.data;
          if (data.code == 1) {
            this.getUploadVideoList = data.data.list;
            this.videoTotal = data.data.total;
            this.getUploadVideoList.forEach((uvideo) => {
              this.$set(uvideo, 'selected', false);
              this.videoLists.forEach((video) => {
                if (uvideo.path == video.srcpath) {
                  this.$set(uvideo, 'selected', true);
                }
              });
            });
          } else {
            this.$Message.error(data.message);
          }
        })
        .catch((err) => {
          console.log(res);
        });
    },
    asyncOK() {
      if (!this.userVideoName) {
        this.$Message.warning('请先选择视频！');
        this.addVideoLoading = false;
        setTimeout(() => {
          this.addVideoLoading = true;
        });
        return;
      }
      let formData = {};
      formData.srcpath = this.userVideoPath;
      formData.srcname = this.userVideoName;
      formData.ispublic = 1;
      formData.createtime = '';
      formData.downloadtimes = 0;
      formData.isdownload = 1;
      formData.creator = this.USER_ID;
      formData.ecid = this.ecid;
      formData.srclocation = 1;
      formData.duration = this.userVideo.duration || 0;
      if (this.videoLists.length == 0) {
        addExpVideo(formData)
          .then((data) => {
            if (data.code == 1) {
              this.$Message.success('视频添加成功！');
              this.addVideoModal = false;
              this.addVideoLoading = false;
              this.getVideoList();
            } else {
              this.$Message.error('视频添加失败！');
            }
          })
          .catch((err) => {
            console.log(err);
          });
      } else {
        modifyExpVideo(this.videoLists[0].srcid, formData)
          .then((data) => {
            // console.log(res)
            if (data.code == 1) {
              this.$Message.success('视频更新成功！');
              this.addVideoModal = false;
              this.addVideoLoading = false;
              this.getVideoList();
            } else {
              this.$Message.error('视频添加失败！');
            }
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },
    useVideo(params) {
      this.userVideoName = params.row.originName;
      this.userVideoPath = params.row.path;
      this.userVideo = params.row;
      this.getUploadVideoList.forEach((uvideo) => {
        this.$set(uvideo, 'selected', false);
        this.videoLists.forEach((video) => {
          if (uvideo.path == video.srcpath || uvideo.path == this.userVideoPath) {
            this.$set(uvideo, 'selected', true);
          }
        });
      });
      let video = this.getUploadVideoList.filter((video) => video.id == params.row.id)[0];
      this.$set(video, 'selected', true);
    },
    // 删除视频
    deleteVideo(item) {
      let srcId = item.srcid;
      let ecId = this.ecid;
      delExpVideo(srcId)
        .then((data) => {
          // console.log(res)
          if (data.code == 1) {
            this.$Message.success('删除成功！');
            this.getVideoList();
          } else {
            this.$Message.error({
              content: data.message,
              duration: 3
            });
          }
        })
        .catch((err) => {
          console.log(err);
          this.$Message.error('服务连接失败！');
        });
    },
    cancel() {},
    changePage(page) {
      this.queryVideoInfo.pageIndex = page;
      this.queryUploadList();
    },
    gotoDoc() {
      window.openTrain('/api/minio/filePreview?path=' + this.videoLists[0].srcpath, '_blank');
    },
    loadDoc() {
      this.docLoadCompete = true;
      let returnData = '';
      if (document.getElementById('expDoc').contentDocument) {
        returnData = document.getElementById('expDoc').contentDocument.body.innerText;
      }
      try {
        let data = JSON.parse(returnData);
        this.docLoaded = false;
        this.loadErrorMessage = data.message;
      } catch (e) {
        this.docLoaded = true;
        this.loadErrorMessage = '';
      }
    }
  },
  destroyed() {}
};
</script>

<style scoped>
.video-wrap {
  position: relative;
  margin-bottom: 5px;
  padding-left: 10px;
}
.video-wrap:after {
  content: '';
  clear: both;
  display: block;
}
/* 省略图 */
.defGraphWrap {
  width: 100%;
  height: calc(100vh - 295px);
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}
.defGraph {
  height: 126px;
  width: 157px;
  background: url('../../../assets/globalIcon/defGraph.png') no-repeat center center;
  background-size: 157px 126px;
}
.graphText {
  color: #888;
  font-size: 14px;
  text-align: center;
  margin-top: 20px;
}
.expDoc {
  height: calc(100vh - 320px);
}
</style>
